import datetime
import os
from shutil import move
from os import path, makedirs

import PyPDF2
from celery import group
from celery.result import allow_join_result
from pdfkit import from_url
import zipfile

from app import celery
from app.libs.pdfWaterMark import WaterMarkUtils


@celery.task
def mk_pdf(url, cookies, path):
    options = {
        "cookie": [(c, cookies.get(c)) for c in cookies],
        "footer-center": "[page]/[topage]",
        "margin-top": "20mm",
        "margin-bottom": "20mm",
        "footer-font-size": 9,
        "footer-font-name": "STSongti",
    }
    from_url("http://localhost:5002" + url, path, options=options)
    return f"{path}生成完毕"


@celery.task
def add_watermark(pdf_file, content):
    wm_file = f"{content}.pdf"
    if not os.path.exists(wm_file):
        wm_file = WaterMarkUtils(content).save()
    wm_reader = PyPDF2.PdfReader(wm_file)
    wm = wm_reader.pages[0]
    source_reader = PyPDF2.PdfReader(pdf_file)
    target_writer = PyPDF2.PdfWriter()
    for page in source_reader.pages:
        page.merge_page(wm)
        target_writer.add_page(page)
    with open(pdf_file, "wb") as write_file:
        target_writer.write(write_file)
    return f"{pdf_file}水印添加完毕"


@celery.task
def mk_zip_and_pdf(co_id, files, mk_pdf_args_list):
    r = group([mk_pdf.s(*mk_pdf_args) for mk_pdf_args in mk_pdf_args_list])()
    with allow_join_result():
        r.get()
    # if watermark:
    #     content = "天衡会计师事务所（特殊普通合伙）苏州安信分所"
    #     r = group([add_watermark.s(pdf_file, content) for pdf_file in files])()
    #     with allow_join_result():
    #         r.get()
    with zipfile.ZipFile("app/static/zip/{}.zip".format(co_id), "w") as z:
        n = 0
        for f in files:
            n += 1
            z.write(f, str(n) + "_" + f.split("/")[-1][len(str(co_id)) + 1 :])
    return "zip打包完毕"


@celery.task
def cut_logs():
    print("cut_logs")
    PATH = "/root/confirmation"
    makedirs(path.join(PATH, "logs"), exist_ok=True)
    move(
        path.join(PATH, "server.log"),
        path.join(
            PATH,
            "logs",
            "uwsgi_" + datetime.datetime.now().strftime("%Y-%m-%d") + ".log",
        ),
    )
    move(
        path.join(PATH, "celery.log"),
        path.join(
            PATH,
            "logs",
            "celery_" + datetime.datetime.now().strftime("%Y-%m-%d") + ".log",
        ),
    )
    open(path.join(PATH, "touchforlogrotat"), "w").close()
    open(path.join(PATH, "celery.log"), "w").close()
